<template>
	<view>
		<u-notify ref="uNotify"></u-notify>
		<!-- <u-button type="primary" text="申请保养" @click="add"></u-button> -->
		<!-- <u-search v-model="keyword" :show-action="false" @change="searchlist" placeholder="请输入关键字"></u-search> -->
		<u-list @scrolltolower="scrolltolower" v-if="maintenanceList != false || status == 'loading'">
			<u-list-item v-for="(item, index) in maintenanceList" :key="index">
				<u-cell :title="(index+1)+'、'+ item.MaintenanceItems" @click="openPage(item.Id)" :name="item.Id">
					<view slot="label" style="font-size: 12px;color: #909193;line-height: 18px;">
						<span>{{'保养时间:' + (item.ManitenanceTime || '') + ' 此次保养里程:' + (item.CurrentMileage || '') 
						+ ' 办理人:' + (item.Agent || '')}}</span>
					</view>
					<view slot="right-icon"
					style="display: flex;flex-direction: row; justify-content: center;align-items: center">
						<u-button type="primary" 
						v-if="item.Status == '已审核' && item.CreatorId == user.Id" 
						@click.native.stop="toFinish(item)">完成保养</u-button>
						<view v-if="item.Creator.Id == user.Id && item.Status != '已完成'" 
						style="margin-left: 3px; color: red; font-size: 14px;"
							@click.native.stop="toDel(item.Id)">撤回</view>
					</view>
					<!-- <u-avatar slot="icon" shape="square" size="65"
						:src="item.ImageList[0]? `https://project.gxrunxiang.com/SysFile/download?id=${item.ImageList[0].Id}` : ''"
						customStyle="margin: -3px 5px -3px 0"></u-avatar> -->
				</u-cell>
			</u-list-item>
			<u-modal title="信息" :show="modalShow" @confirm="finish" :closeOnClickOverlay="true"
				@close="modalShow = false" style="z-index: 998;">
				<u--form labelWidth="auto" labelPosition="top" ref="uForm" :rules="rules" :model="finishForm">
					<u-form-item label="是否维修" prop="IsRepairs" name="IsRepairs" :required="true">
						<u-radio-group v-model="finishForm.IsRepairs" placement="row" @change="IsRepairsChange">
							<u-radio label="是" :name='true'></u-radio>
							<u-radio label="否" :name='false'></u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="保养费用/维修费用(元)" :required="true" name="MaintenanceCosts" prop="MaintenanceCosts"><u--input
							v-model="finishForm.MaintenanceCosts" placeholder="请输入"
							type="number"></u--input></u-form-item>
					<u-form-item label="此次保养时里程" :required="true" name="CurrentMileage" prop="CurrentMileage"><u--input
							v-model="finishForm.CurrentMileage" placeholder="请输入此次保养时里程"
							type="number"></u--input></u-form-item>
					<u-form-item label="备注" name="Remark" prop="Remark"><u-textarea
							v-model="finishForm.Remark" placeholder="请输入备注"
							></u-textarea></u-form-item>
					<u-form-item label="附件照片"><u-upload :fileList="fileList1" @afterRead="afterRead"
							@delete="deletePic" name="1" multiple itype='附件照片' :sizeType='["compressed"]'
							:maxCount="10"></u-upload></u-form-item>
					<!-- <u-form-item>
						<jp-signature-popup v-model="image" :openSmooth="true" />
					</u-form-item> -->
				</u--form>
			</u-modal>
			<u-modal :show="delmodalShow" title="提示" content='确认撤回申请?' @confirm="del" :showCancelButton="true"
				confirmText="是" cancelText="否" @cancel="delmodalShow = false" :closeOnClickOverlay="true"
				@close="delmodalShow = false"></u-modal>
			<u-loadmore :status="status" v-if="loading" />
		</u-list>
		<u-empty mode="data" icon="https://project.gxrunxiang.com/cdn/list.png" v-else>
		</u-empty>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '@/common/config.js'
	import {
		getmaintenancelist,
		addcarapply,
		delmaintenance,
		maintenanceupdate
	} from '@/common/api.js'
	export default {
		data() {
			return {
				maintenanceList: [],
				keyword: "",
				notifyData: {
					message: '成功',
					type: 'success',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 3000,
					safeAreaInsetTop: false
				},
				pageIndex: 1, //当前页数
				pageSize: 20, //页数大小
				totalPage: "", //总页数
				total: 0, //数据总数
				status: 'loadmore', //加载状态
				loading: true,
				token: "",
				user: {},
				keyword: "",
				userfilter: {},
				carId: "",
				delId: "",
				delmodalShow: false,
				modalShow: false,
				finishForm: {
					IsRepairs: "",
					MaintenanceCosts: "",
					CurrentMileage: "",
					Remark: ""
				},
				update: {},
				applyId: "",
				rules: {
					'IsRepairs': {
						type: 'boolean',
						required: true,
						message: '请选择是否维修',
						trigger: ['blur']
					},
					'MaintenanceCosts': {
						required: true,
						message: '请输入保养费用/维修费用',
						trigger: ['blur']
					},
					'CurrentMileage': {
						required: true,
						message: '请输入此次保养里程',
						trigger: ['blur']
					},
				},
				fileList1: [],
				itypelist: {
					"1": "附件照片",
				},
			}
		},
		onLoad(option) {
			this.user = JSON.parse(uni.getStorageSync("$userinfo"))
			this.carId = option.Id
			this.token = uni.getStorageSync("$token")
		},
		onShow() {
			this.maintenanceList = []
			this.getlist()
		},
		onReady() {
				// #ifdef MP-WEIXIN || MP-QQ || MP-BAIDU 
				//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		    	this.$refs.uForm.setRules(this.rules)
				// #endif
		},
		methods: {
			openPage(Id) {
				uni.navigateTo({
					url: "maintenancedetail?Id=" + Id
				})
			},
			async getlist() {
				this.status = 'loading'
				// let querytype = this.$route.query.querytype
				let para = {
					Parameters: [],
				}
				para.Parameters.push({
					FieldName: "carId",
					ConditionalType: "Equal",
					FieldValue: this.carId,
				})
				para.OrderBys = ['CreateTime desc']
				para.pageSize = this.pageSize
				para.pageIndex = this.pageIndex
				await getmaintenancelist(para).then(res => {
					let data = res.data
					this.maintenanceList.push(...data)
					this.total = res.count
					this.totalPage = Math.ceil(this.total / this.pageSize)
				})
				if (this.maintenanceList.length < this.pageSize) {
					this.loading = false; //如果数据列表小于当前页数，就让加载标签消失
					this.status = 'nomore';
				} else {
					this.status = 'loadmore';
				}
			},
			scrolltolower() {
				// 如果当前页数大于等于总页数，状态修改为没有更多了，不再继续往下执行代码
				if (this.pageIndex >= this.totalPage) {
					this.status = 'nomore';
					return;
				};
				this.status = 'loading'; //状态改为加载中
				this.pageIndex = ++this.pageIndex; //页面新增一页
				this.getlist(); //修改页数后，重新获取数据
			},
			// async searchlist() {
			// 	this.maintenanceList = [] //初始化
			// 	this.pageIndex = 1 //初始化当前页数为1
			// 	this.loading = true
			// 	await this.getlist()
			// },
			add() {
				uni.navigateTo({
					url: "addmaintenance?CarId=" + this.carId
				})
			},
			toFinish(item){
				this.update = item
				this.applyId = item.Id
				this.modalShow = true
			},
			finish(){
				this.update.IsRepairs = this.finishForm.IsRepairs
				this.update.MaintenanceCosts = this.finishForm.MaintenanceCosts
				this.update.CurrentMileage = this.finishForm.CurrentMileage
				this.update.Remark = this.finishForm.Remark
				this.$refs.uForm.validate().then(res => {
					maintenanceupdate(this.update).then(res => {
						if(res == true){
							this.$refs.uNotify.show(this.notifyData)
								setTimeout(() => {
									this.maintenanceList = []
									this.modalShow = false
									this.getlist()
								}, 1000)}
						})
					}).catch(errors => {
						uni.$u.toast('请填写必填参数！')
					})	
			},
			toDel(Id) {
				this.delId = Id
				this.delmodalShow = true
			},
			del() {
				let ids = []
				ids.push(this.delId)
				delmaintenance(ids).then((res) => {
					if (res == true)
						this.maintenanceList = []
						this.delmodalShow = false
						this.getlist()
				})
			},
			IsRepairsChange(e){
				if(e == true){
					this.finishForm.IsRepairs = true
				}else{
					this.finishForm.IsRepairs = false
				}
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {				console.log(event.name);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, this.itypelist[event.name])
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, itype) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}/SysFile/upload?outid=${this.applyId || this.user.Id}&type=附件照片`,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"Authorization": `Bearer ${this.token}`
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
		},
	}
</script>

<style>

</style>